package crond

import (
	"context"
	"mini-app/internal/app/grpc/client"
	"mini-app/internal/app/grpc/protoc/advertisingc"
	"mini-app/internal/dal"
	"mini-app/internal/define"
	"time"

	"192.168.1.75/go-pkg/logx"
)

func CheckUnpaidAdvertisementOrder() error {

	// 查询1小时前未支付的订单
	ctx := context.Background()
	oneHourAgo := time.Now().Add(-1 * time.Hour).Unix()

	o := dal.Q.Advertisement
	tx := o.WithContext(ctx)

	orders, err := tx.Where(o.Status.Eq(define.AdOrderStatusUnpaid)).Where(o.CreatedAt.Lte(oneHourAgo)).Find()
	if err != nil {
		logx.Error(ctx, "查询未支付超时订单失败", logx.Any("error", err))
		return err
	}

	if len(orders) == 0 {
		logx.Info(ctx, "没有超时未支付订单")
		return nil
	}
	// 将超时未支付订单状态改为已关闭
	for _, order := range orders {
		_, err := tx.Where(o.ID.Eq(order.ID)).Update(o.Status, define.AdOrderStatusUnpaidClosed)
		if err != nil {
			logx.Error(ctx, "更新订单状态失败", logx.Any("orderID", order.ID), logx.Any("error", err))
			continue
		}
		logx.Info(ctx, "关闭超时未支付订单", logx.Any("orderID", order.ID))

		client, err := client.GetAdvertisingClient()
		if err != nil {

		}

		var params advertisingc.SPublishScheduleChangeStatusReq
		params.Id = order.ScheduleID
		params.MerchantId = ""
		params.Status = define.ORDER_FAILED
		_, err = client.ScheduleChangeStatus(ctx, &params)
		if err != nil {

		}

	}

	return nil
}
